import { isEqual } from 'lodash';
import XLSX from 'xlsx';

/**
 * 去除对象中所有符合条件的对象
 * @param {Object} obj 来源对象
 * @param {Function} fn 函数验证每个字段
 */
function compactObj(obj: any, fn: any) {
  // eslint-disable-next-line no-restricted-syntax
  for (const i in obj) {
    if (obj.hasOwnProperty(i)) {
      if (typeof obj[i] === 'object') {
        compactObj(obj[i], fn);
      }
      if (fn(obj[i])) {
        // eslint-disable-next-line no-param-reassign
        delete obj[i];
      }
    }
  }
}

// 是否为空对象, '', null或undefined
function isEmpty(foo: any) {
  if (typeof foo === 'object') {
    // eslint-disable-next-line no-restricted-syntax
    for (const i in foo) {
      if (foo.hasOwnProperty(i)) {
        return false;
      }
    }
    return true;
  }
  return foo === '' || foo === null || foo === undefined;
}

// 删除值空对象, '', null, undefined的属性
export const clean = (obj: any) => {
  return compactObj(obj, isEmpty);
};

/**
 * cos 文件路径外包同学不能直接访问, 并且图片/XML等文件不能直接在浏览器打开,必须通过一层代理服务访问
 * @param {String} path cos文件地址
 * @param {Boolean} [forceDownload=false] - 是否强制下载
 */
export function getPreviewUrl(path: string, forceDownload = false) {
  return `/api/cos/previewFile?cosPath=${encodeURIComponent(path)}&download=${
    forceDownload ? 1 : 0
  }`;
}

export function getDownloadUrl(path: string) {
  return `/api/cos/downloadFile?cosPath=${encodeURIComponent(path)}`;
}

export function downloadByUrlListLoop(mediaPaths: string[]) {
  if (mediaPaths[0]) {
    const id = String(Math.random());
    window.open(getDownloadUrl(mediaPaths[0]), id);
    setTimeout(() => {
      downloadByUrlListLoop(mediaPaths.slice(1, mediaPaths.length));
    }, 0);
  }
}

// todo 增加权限控制，目前是直接当成admin
export const isAdmin = true;

// 修复滚动穿透的问题
export const drawerOrModalVisibleChange = (visible: boolean) => {
  if (visible) {
    setTimeout(() => {
      document.body.style.overflow = 'hidden';
    }, 200);
  } else {
    document.body.style.overflow = 'auto';
  }
};

/**
 * 把对象转化为查询串
 *
 * @export
 * @param {Object} obj
 * @returns
 */
export function objectToQuery(obj: any) {
  const queryList: string[] = [];

  if (typeof obj !== 'object') return '';

  Object.keys(obj).forEach((key) => {
    const t = typeof obj[key];
    if (t === 'number' || t === 'string' || t === 'boolean') {
      queryList.push(`${key}=${encodeURIComponent(obj[key])}`);
    } else {
      queryList.push(`${key}=${encodeURIComponent(JSON.stringify(obj[key]))}`);
    }
  });

  return queryList.join('&');
}

// 获取起始-结束区间的数字数组
export function numberRange(start: number, end: number) {
  const result = [];
  for (let i = start; i < end; i += 1) {
    result.push(i);
  }
  return result;
}

export const isSingersEqual = (singers: any[], dataSourceSingers: any[]) => {
  const singerIds = singers?.map((singer) => singer.singerId);
  const dataSourceSingerIds = dataSourceSingers?.map((singer) => singer.singerId);
  return isEqual(singerIds, dataSourceSingerIds);
};

export const listToOptions = (sourceData: any[], idKey: string, nameKey: string) => {
  const list = Array.isArray(sourceData) ? sourceData : [];
  const options = list.map((itemInfo) => {
    return {
      value: itemInfo[idKey],
      text: `${itemInfo[idKey]}-@-${itemInfo[nameKey]}`,
    };
  });
  return options;
};

export const buildSearchTypeDefaultValue = (
  searchType: string | number,
  searchTypeValue?: string | number,
) => {
  return {
    [searchType]: searchTypeValue,
    searchType,
  };
};

export const downloadTable = (id: string, fileName: string) => {
  const items = document.getElementById(id);
  const workbook = XLSX.utils.table_to_book(items);
  XLSX.writeFile(workbook, `${fileName}.xlsx`);
};

/**
 * 删除url中的某个参数
 * @param {String} URL 地址，例如http://www.domain.com/?user=anonymous&id=123&id=456&city=%E5%8C%97%E4%BA%AC&enabled
 * @param {String} key 指定的key
 * @return {String} URL 删除指定参数后的URL
 */
export function deleteUrlQuery(url = '', key = '') {
  const regExp = new RegExp(`[\\&\\?]${key}=([^&#]+)`, 'g');
  return url.replace(regExp, '');
}
